<template>
  <div class="profile-container">
    <div class="content" v-loading="loading">
      <div class="profile-header">
        <div class="avatar-wrapper">
          <el-avatar :size="100" :src="userInfo?.avatar">
            {{ userInfo?.nickname?.[0] }}
          </el-avatar>
          <el-upload
            :show-file-list="false"
            :before-upload="beforeAvatarUpload"
            :http-request="handleAvatarUpload"
            class="avatar-uploader"
          >
            <el-button size="small" type="primary" circle class="upload-btn">
              <el-icon><Upload /></el-icon>
            </el-button>
          </el-upload>
        </div>
        <div class="info">
          <h2>{{ userInfo?.nickname }}</h2>
          <p class="username">@{{ userInfo?.username }}</p>
          <div class="stats">
            <div class="stat-item">
              <span class="value">{{ userInfo?.points || 0 }}</span>
              <span class="label">积分</span>
            </div>
            <div class="stat-item">
              <span class="value">{{ userInfo?.creditScore || 100 }}</span>
              <span class="label">信誉分</span>
            </div>
          </div>
        </div>
      </div>

      <el-tabs v-model="activeTab">
        <el-tab-pane label="基本信息" name="info">
          <el-form :model="form" label-width="100px" class="profile-form">
            <el-form-item label="昵称">
              <el-input v-model="form.nickname" />
            </el-form-item>
            <el-form-item label="邮箱">
              <el-input v-model="form.email" />
            </el-form-item>
            <el-form-item label="手机号">
              <el-input v-model="form.phone" />
            </el-form-item>
            <el-form-item label="学校">
              <el-input v-model="form.school" />
            </el-form-item>
            <el-form-item label="专业">
              <el-input v-model="form.major" />
            </el-form-item>
            <el-form-item label="年级">
              <el-input v-model="form.grade" />
            </el-form-item>
            <el-form-item label="个人简介">
              <el-input v-model="form.bio" type="textarea" :rows="4" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleUpdate" :loading="updating">
                保存修改
              </el-button>
              <el-button @click="handleLogout">退出登录</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>

        <el-tab-pane label="我的技能" name="skills">
          <div class="skill-list" v-loading="skillLoading">
            <el-empty v-if="mySkills.length === 0" description="还没有发布技能" />
            <div v-for="skill in mySkills" :key="skill.id" class="skill-item">
              <div class="skill-info-row">
                <h4>{{ skill.title }}</h4>
                <div>
                  <el-button size="small" @click="router.push(`/skill/detail/${skill.id}`)">查看</el-button>
                  <el-button size="small" type="danger" @click="deleteSkill(skill.id)">删除</el-button>
                </div>
              </div>
              <p>{{ skill.description }}</p>
              <div class="skill-stats">
                <span><el-icon><View /></el-icon> {{ skill.viewCount }}</span>
                <span><el-icon><Star /></el-icon> {{ skill.favoriteCount }}</span>
                <span><el-icon><Calendar /></el-icon> {{ skill.appointmentCount }}</span>
              </div>
            </div>
          </div>
        </el-tab-pane>

        <el-tab-pane label="我的收藏" name="favorites">
          <div class="skill-list" v-loading="favoriteLoading">
            <el-empty v-if="myFavorites.length === 0" description="还没有收藏技能" />
            <div v-for="skill in myFavorites" :key="skill.id" class="skill-item">
              <div class="skill-info-row">
                <h4>{{ skill.title }}</h4>
                <el-button size="small" @click="router.push(`/skill/detail/${skill.id}`)">查看</el-button>
              </div>
              <p>{{ skill.description }}</p>
              <div class="skill-stats">
                <span><el-icon><View /></el-icon> {{ skill.viewCount }}</span>
                <span><el-icon><Star /></el-icon> {{ skill.favoriteCount }}</span>
              </div>
            </div>
          </div>
        </el-tab-pane>

        <el-tab-pane label="收到的评价" name="reviews">
          <div class="review-list" v-loading="reviewLoading">
            <el-empty v-if="myReviews.length === 0" description="还没有收到评价" />
            <div v-for="review in myReviews" :key="review.id" class="review-item">
              <div class="review-header">
                <div class="reviewer-info">
                  <el-avatar :size="40" :src="review.reviewerAvatar">
                    {{ review.reviewerNickname?.[0] }}
                  </el-avatar>
                  <div>
                    <div class="reviewer-name">{{ review.reviewerNickname }}</div>
                    <el-rate v-model="review.rating" disabled show-score />
                  </div>
                </div>
                <span class="review-time">{{ formatReviewTime(review.createTime) }}</span>
              </div>
              <div class="review-content">
                {{ review.content }}
              </div>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useUserStore } from '@/stores/user'
import { updateUser } from '@/api/auth'
import { getMySkills, getMyFavorites, deleteSkill as deleteSkillApi } from '@/api/skill'
import { uploadImage } from '@/api/file'
import { getUserReviews } from '@/api/review'
import dayjs from 'dayjs'

const router = useRouter()
const userStore = useUserStore()

const loading = ref(false)
const updating = ref(false)
const skillLoading = ref(false)
const favoriteLoading = ref(false)
const reviewLoading = ref(false)
const activeTab = ref('info')
const userInfo = ref(null)
const mySkills = ref([])
const myFavorites = ref([])
const myReviews = ref([])

const form = reactive({
  nickname: '',
  email: '',
  phone: '',
  school: '',
  major: '',
  grade: '',
  bio: ''
})

const fetchUserInfo = async () => {
  loading.value = true
  try {
    await userStore.fetchUserInfo()
    userInfo.value = userStore.userInfo
    Object.assign(form, {
      nickname: userInfo.value.nickname,
      email: userInfo.value.email,
      phone: userInfo.value.phone,
      school: userInfo.value.school,
      major: userInfo.value.major,
      grade: userInfo.value.grade,
      bio: userInfo.value.bio
    })
  } catch (error) {
    console.error('获取用户信息失败：', error)
  } finally {
    loading.value = false
  }
}

const fetchMySkills = async () => {
  skillLoading.value = true
  try {
    const res = await getMySkills({ page: 1, size: 100 })
    mySkills.value = res.data.records || []
  } catch (error) {
    console.error('获取技能列表失败：', error)
  } finally {
    skillLoading.value = false
  }
}

const fetchMyFavorites = async () => {
  favoriteLoading.value = true
  try {
    const res = await getMyFavorites({ page: 1, size: 100 })
    myFavorites.value = res.data.records || []
  } catch (error) {
    console.error('获取收藏列表失败：', error)
  } finally {
    favoriteLoading.value = false
  }
}

const fetchMyReviews = async () => {
  if (!userInfo.value?.id) return
  
  reviewLoading.value = true
  try {
    const res = await getUserReviews(userInfo.value.id, 1, 100)
    myReviews.value = res.data.records || []
  } catch (error) {
    console.error('获取评价列表失败：', error)
  } finally {
    reviewLoading.value = false
  }
}

const formatReviewTime = (time) => {
  return dayjs(time).format('YYYY-MM-DD HH:mm')
}

const handleUpdate = async () => {
  updating.value = true
  try {
    await updateUser(form)
    ElMessage.success('更新成功')
    await fetchUserInfo()
  } catch (error) {
    console.error('更新失败：', error)
  } finally {
    updating.value = false
  }
}

const deleteSkill = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除此技能吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    await deleteSkillApi(id)
    ElMessage.success('删除成功')
    fetchMySkills()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败：', error)
    }
  }
}

const handleLogout = async () => {
  try {
    await ElMessageBox.confirm('确定要退出登录吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    userStore.logout()
    router.push('/login')
  } catch {}
}

const beforeAvatarUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt5M = file.size / 1024 / 1024 < 5

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt5M) {
    ElMessage.error('图片大小不能超过 5MB!')
    return false
  }
  return true
}

const handleAvatarUpload = async ({ file }) => {
  try {
    const res = await uploadImage(file)
    form.avatar = res.data.url
    await updateUser(form)
    ElMessage.success('头像上传成功')
    await fetchUserInfo()
  } catch (error) {
    console.error('头像上传失败：', error)
  }
}

watch(activeTab, (val) => {
  if (val === 'skills' && mySkills.value.length === 0) {
    fetchMySkills()
  } else if (val === 'favorites' && myFavorites.value.length === 0) {
    fetchMyFavorites()
  } else if (val === 'reviews' && myReviews.value.length === 0) {
    fetchMyReviews()
  }
})

onMounted(() => {
  fetchUserInfo()
})
</script>

<style scoped>
.profile-container {
  min-height: 100%;
  padding: 30px 20px;
  animation: fadeIn 0.6s ease-out;
}

.content {
  max-width: 1200px;
  margin: 0 auto;
  background: white;
  border-radius: 20px;
  overflow: hidden;
  box-shadow: 0 8px 32px rgba(102, 126, 234, 0.12);
  border: 1px solid rgba(102, 126, 234, 0.1);
}

.profile-header {
  display: flex;
  align-items: center;
  gap: 40px;
  padding: 50px 60px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  position: relative;
  overflow: hidden;
}

.profile-header::before {
  content: '';
  position: absolute;
  top: -50%;
  right: -20%;
  width: 400px;
  height: 400px;
  background: radial-gradient(circle, rgba(255, 255, 255, 0.1) 0%, transparent 70%);
  animation: pulse 4s ease-in-out infinite;
}

.avatar-wrapper {
  position: relative;
  z-index: 1;
}

.avatar-wrapper :deep(.el-avatar) {
  border: 4px solid rgba(255, 255, 255, 0.3);
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.2);
}

.avatar-uploader {
  position: absolute;
  bottom: 0;
  right: 0;
  z-index: 2;
}

.upload-btn {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
  transition: all 0.3s;
}

.upload-btn:hover {
  transform: scale(1.1);
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.4);
}

.info {
  flex: 1;
  z-index: 1;
}

.info h2 {
  font-size: 32px;
  font-weight: 800;
  margin-bottom: 8px;
  letter-spacing: -0.5px;
}

.username {
  font-size: 16px;
  opacity: 0.9;
  margin-bottom: 24px;
  font-weight: 500;
}

.stats {
  display: flex;
  gap: 50px;
}

.stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 16px 24px;
  background: rgba(255, 255, 255, 0.15);
  backdrop-filter: blur(10px);
  border-radius: 12px;
  min-width: 100px;
  transition: all 0.3s;
}

.stat-item:hover {
  background: rgba(255, 255, 255, 0.25);
  transform: translateY(-4px);
}

.stat-item .value {
  font-size: 28px;
  font-weight: 800;
  margin-bottom: 4px;
}

.stat-item .label {
  font-size: 14px;
  opacity: 0.95;
}

.content :deep(.el-tabs) {
  padding: 0 40px 40px;
}

.content :deep(.el-tabs__header) {
  margin-bottom: 30px;
}

.content :deep(.el-tabs__item) {
  font-size: 16px;
  font-weight: 600;
  padding: 0 24px;
}

.content :deep(.el-tabs__item.is-active) {
  color: #667eea;
}

.content :deep(.el-tabs__active-bar) {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  height: 3px;
}

.profile-form {
  max-width: 700px;
  padding: 20px 0;
}

.profile-form :deep(.el-form-item__label) {
  font-weight: 600;
  color: #333;
}

.profile-form :deep(.el-input__wrapper),
.profile-form :deep(.el-textarea__inner) {
  border-radius: 8px;
}

.skill-list {
  padding: 0;
}

.skill-item {
  padding: 24px;
  border: 1px solid #f0f2f5;
  border-radius: 16px;
  margin-bottom: 20px;
  transition: all 0.3s;
  background: white;
}

.skill-item:hover {
  border-color: #667eea;
  box-shadow: 0 8px 24px rgba(102, 126, 234, 0.15);
  transform: translateY(-4px);
}

.skill-info-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.skill-info-row h4 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.skill-item p {
  color: #666;
  margin-bottom: 16px;
  line-height: 1.6;
}

.skill-stats {
  display: flex;
  gap: 24px;
  font-size: 14px;
  color: #999;
  font-weight: 500;
  padding-top: 12px;
  border-top: 1px solid #f0f2f5;
}

.skill-stats span {
  display: flex;
  align-items: center;
  gap: 6px;
  transition: color 0.3s;
}

.skill-stats span:hover {
  color: #667eea;
}

.review-list {
  padding: 0;
}

.review-item {
  padding: 24px;
  border: 1px solid #f0f2f5;
  border-radius: 16px;
  margin-bottom: 20px;
  background: white;
  transition: all 0.3s;
}

.review-item:hover {
  border-color: #667eea;
  box-shadow: 0 8px 24px rgba(102, 126, 234, 0.15);
  transform: translateY(-4px);
}

.review-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 16px;
  padding-bottom: 16px;
  border-bottom: 1px solid #f0f2f5;
}

.reviewer-info {
  display: flex;
  gap: 12px;
}

.reviewer-info :deep(.el-avatar) {
  border: 2px solid #f0f2f5;
}

.reviewer-name {
  font-weight: 600;
  margin-bottom: 6px;
  font-size: 16px;
  color: #333;
}

.review-time {
  font-size: 13px;
  color: #999;
}

.review-content {
  color: #666;
  line-height: 1.8;
  font-size: 15px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .profile-container {
    padding: 20px 12px;
  }

  .content {
    border-radius: 12px;
  }

  .profile-header {
    flex-direction: column;
    text-align: center;
    padding: 40px 24px;
  }

  .info h2 {
    font-size: 24px;
  }

  .stats {
    gap: 20px;
    justify-content: center;
  }

  .content :deep(.el-tabs) {
    padding: 0 20px 20px;
  }

  .skill-item,
  .review-item {
    padding: 16px;
  }

  .skill-info-row {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }
}
</style>

